package com.chenjun.web.controller.sys;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chenjun.common.Constant;
import com.chenjun.common.model.DataGridModel;
import com.chenjun.common.model.DataGridSortModel;
import com.chenjun.core.dao.generator.entity.SysResource;
import com.chenjun.core.dao.generator.entity.SysUser;
import com.chenjun.core.service.sys.SysResourceService;
import com.chenjun.core.vo.sys.SilderVo;
import com.chenjun.web.controller.BaseController;

/**
 * 
 * @Description: 菜单控制类
 * @author yanjinyin
 * @date 2017年7月22日 上午8:27:36
 */
@SuppressWarnings("serial")
@Controller
@RequestMapping("menu")
public class MenuController extends BaseController {
	
	@Autowired
	private SysResourceService 	sysResourceService;
	
	/**
	 * 
	 * @Description: 获取左侧菜单资源 
	 * @param request
	 * @return
	 * @author yanjinyin
	 * @date 2017年7月22日 上午8:34:16
	 */
	@RequestMapping(value = "/getSliderMenu")
	@ResponseBody
	public List<SilderVo> getSliderMenu(HttpServletRequest request) {
		SysUser loginUser = super.getLoginUser();
		if (loginUser == null || StringUtils.isBlank(loginUser.getId())) {
			return new ArrayList<SilderVo>(0);
		}
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		String slideMenu = Constant.Session.SLIDER_MENU.toString();
		List<SilderVo> silderDtos = (List<SilderVo>) session.getAttribute(slideMenu);
		if (CollectionUtils.isEmpty(silderDtos) || i18nResourcesFreshed(request)) {
			silderDtos = new ArrayList<SilderVo>(0);
			DataGridModel dgm = new DataGridModel();
			dgm.setStart(0);
			dgm.setRows(0);
			dgm.getParams().put("userId", loginUser.getId());
			dgm.getParams().put("ntype", "2");
			dgm.getSortBy().add(new DataGridSortModel("sort_num", DataGridSortModel.DESC));
			List<SysResource> resources = sysResourceService.doListByCondition(dgm);
			Map<String, List<SysResource>> resourceMap = convert2Map(resources);
			convert2Silder(silderDtos, resourceMap);
			session.setAttribute(slideMenu, silderDtos);
		}
		return silderDtos;
	}
	
	/**
	 * 
	 * @Description:国际化资源刷新 
	 * @param request
	 * @return
	 * @author yanjinyin
	 * @date 2017年7月22日 上午8:36:49
	 */
	private boolean i18nResourcesFreshed(HttpServletRequest request){
		Locale locale =  LocaleContextHolder.getLocale(); 
		String locale_str = locale.toString();
		String pre_locale = (String) request.getSession().getAttribute(Constant.Session.LOCALE_CONTEXT.toString());
		Boolean is_fresh = true;
		if(StringUtils.isNotBlank(pre_locale)){
			if(pre_locale.equals(locale_str)){
				is_fresh = false;
			}
		}
		request.getSession().setAttribute(Constant.Session.LOCALE_CONTEXT.toString(),locale_str);
		return is_fresh;
	} 
	/**
	 * 
	 * @Description: 
	 * @param resources
	 * @return
	 * @author yanjinyin
	 * @date 2017年7月22日 下午2:19:50
	 */
	private Map<String, List<SysResource>> convert2Map(List<SysResource> resources) {
		Map<String, List<SysResource>> map = new HashMap<String, List<SysResource>>();
		for (SysResource resource : resources) {
			if (CollectionUtils.isEmpty(map.get(resource.getParentId()))) {
				map.put(resource.getParentId(), new ArrayList<SysResource>(0));
			}
			map.get(resource.getParentId()).add(resource);
		}
		return map;
	}
	/**
	 * 
	 * @Description:  
	 * @param parentDtos
	 * @param resourceMap
	 * @author yanjinyin
	 * @date 2017年7月22日 下午2:20:00
	 */
	private void convert2Silder(List<SilderVo> parentDtos, Map<String, List<SysResource>> resourceMap) {
		if (parentDtos.isEmpty()) {
			List<SysResource> list = resourceMap.get(Constant.Tree.TOP_FID.toString());
			if (list != null) {
				for (SysResource resource : list) {
					SilderVo dto = new SilderVo();
					dto.setId(resource.getId());
					dto.setName(resource.getName());
					if(StringUtils.isNoneBlank(resource.getI18nKey())){
						dto.setName(getLocaleMessage(resource.getI18nKey()));
					}
					dto.setParentId(resource.getParentId());
					dto.setType(resource.getType());
					dto.setUrl(resource.getUrl());
					dto.setIcon(resource.getIcon());
					parentDtos.add(dto);
				}
				convert2Silder(parentDtos, resourceMap);
			}
		} else {
			for (SilderVo parent : parentDtos) {
				List<SysResource> childrenResources = resourceMap.get(parent.getId());
				if (childrenResources == null || childrenResources.isEmpty()) {
					parent.setHasChild(Constant.State.ENABLED.toString());
				} else {
					parent.setHasChild(Constant.State.DISABLED.toString());
					parent.setChildren(new ArrayList<SilderVo>());
					for (SysResource children : childrenResources) {
						SilderVo dto = new SilderVo();
						dto.setId(children.getId());
						dto.setName(children.getName());
						if(StringUtils.isNoneBlank(children.getI18nKey())){
							dto.setName(getLocaleMessage(children.getI18nKey()));
						}
						dto.setParentId(children.getParentId());
						dto.setType(children.getType());
						dto.setUrl(children.getUrl());
						dto.setIcon(children.getIcon());
						parent.getChildren().add(dto);
					}
					if (!parent.getChildren().isEmpty()) {
						convert2Silder(parent.getChildren(), resourceMap);
					}
				}
			}
		}
	}
	
}
